package com.xiaoxu.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaoxu.auth.dao.UserMapper;
import com.xiaoxu.auth.feignclient.CheckCodeClient;
import com.xiaoxu.auth.model.dto.AuthParamsDto;
import com.xiaoxu.auth.model.dto.UserExt;
import com.xiaoxu.auth.model.po.User;
import com.xiaoxu.auth.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * @author xiaoxu
 * @version 1.0
 * @description 实现账号密码验证登录
 * @date 2023/2/2 15:11
 */
@Service("password_authservice")
public class PasswordAuthService implements AuthService {

    private final UserMapper userMapper;

    private final PasswordEncoder passwordEncoder;

    private final CheckCodeClient checkCodeClient;

    public PasswordAuthService(CheckCodeClient checkCodeClient, PasswordEncoder passwordEncoder, UserMapper userMapper) {
        this.checkCodeClient = checkCodeClient;
        this.passwordEncoder = passwordEncoder;
        this.userMapper = userMapper;
    }

    /**
     * @description 实现账号密码验证
     * @param authParamsDto 认证参数
     * @return UserExt
     */
    @Override
    public UserExt execute(AuthParamsDto authParamsDto) {

        //获取验证码
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
        if (StringUtils.isBlank(checkcodekey) || StringUtils.isBlank(checkcode)){
            throw new RuntimeException("验证码为空");
        }
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (verify == null || !verify){
            throw new RuntimeException("验证码错误");
        }
        //查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,authParamsDto.getUsername());
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            //账户不存在
            throw new RuntimeException("用户账号不存在");
        }
        //获取加密密码
        String password_ser = user.getPassword();
        String password_input = authParamsDto.getPassword();
        //比较密码
        boolean matches = passwordEncoder.matches(password_input, password_ser);
        if (!matches){
            throw new RuntimeException("账号或密码错误!");
        }
        //封装用户信息
        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(user,userExt);
        ArrayList<String> permissions = new ArrayList<>();
        //暂时权限
        permissions.add("p1");
        userExt.setPermissions(permissions);
        return userExt;
    }
}
